package com.mapgis.service

import java.util

import com.fasterxml.jackson.core.JsonParseException
import com.mapgis.constant.Constants
import com.mapgis.pojo._
import com.mapgis.utils.JDBCUtil
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.native.Serialization

import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag



object EventParseService {

    def main(args: Array[String]): Unit = {
//        var eventList = new ListBuffer[util.HashMap[String,String]]
//        val hm1 = new util.HashMap[String,String]()
//        hm1.put("ID","d1f343b89256421c8c8b492f9cf5fb21")
//        hm1.put("IMAGES","{\"creator\":null,\"fileCount\":null,\"height\":0,\"isScan\":null,\"name\":\"2019_11_27_09_06_30_89e64b04699f41b58292cecd36ac5a47.bmp\",\"nameedPath\":\"default/NOW/rappnew/2019/11/27\",\"showName\":\"2019_11_27_09_06_30_89e64b04699f41b58292cecd36ac5a47\",\"size\":177910,\"time\":0,\"title\":\"2019_11_27_09_06_30_89e64b04699f41b58292cecd36ac5a47\",\"userName\":null,\"uuid\":null,\"viewName\":null,\"width\":0}")
//        hm1.put("CONVERSATIONID","d1f343b89256421c8c8b492f9cf5fb21")
//        hm1.put("GATHERID","44030719851224122X")
//        hm1.put("GATHERER","李莉婷")
//        hm1.put("BUILDINGHOUSE","[{\"address\":\"龙苑新村9号\",\"code\":\"4403070050025100107\",\"areaid\":\"440307015001112000\",\"houseid\":\"null\",\"gis_x\":\"null\",\"gis_y\":\"null\",\"buildingid\":\"4403070050025100107\"}]")
//        hm1.put("SQR","[{\"javaClass\":\"com.longrise.LEAP.Base.Objects.EntityBean\",\"type\":\"1\",\"pname\":\"李莉婷\",\"age\":\"\",\"cardno\":\"\",\"address\":\"\",\"phone\":\"13925280578\"},{\"javaClass\":\"com.longrise.LEAP.Base.Objects.EntityBean\",\"type\":\"1\",\"pname\":\"李莉婷\",\"age\":\"\",\"cardno\":\"\",\"address\":\"\",\"phone\":\"13925280578\"}]")
//        hm1.put("DW","[]")
//        hm1.put("REPORTEDDATE","2019/11/27 09:03:18.000000000")
//        hm1.put("CREATOR","李莉婷")
//        hm1.put("COMENUM","1")
//        hm1.put("SOURCE","6")
//        hm1.put("AIM","1")
//        hm1.put("REPORTEDNUM","1")
//        hm1.put("PLACE","龙苑新村9号")
//        hm1.put("AMOUNT",null)
//        hm1.put("EVENTSUMMARY",null)
//        hm1.put("CONTENT","根据网格员龚苏琼排查发现布新九巷2号501.601房该地址存在\"分别于2020年6月28日,2020年7月6日,2020年7月17日上门，该房间未主动申报身份信息\"人口房屋隐患")
//        hm1.put("ISHOUSE","1")
//        hm1.put("ISGROUP","0")
//        hm1.put("EMERGENCY","1")
//        hm1.put("EVENTTYPE","020706")
//        hm1.put("KIND","2")
//        hm1.put("SUBKIND","207")
//        hm1.put("THREEKIND","20706")
//        hm1.put("LOCATION","114.225601;22.668813")
//        hm1.put("GISP_X","114.225601")
//        hm1.put("GISP_Y","22.668813")
//        hm1.put("CODETYPENAME",null)
//        hm1.put("AREAID","440307015001112000")
//        hm1.put("DISTRICTCODE","440307005002112")
//        hm1.put("ACCEPTDEPARTMENT","440307005002112")
//        hm1.put("GRIDID","440307005002112")
//        eventList.+=(hm1).toList
//
////        getImpEventFromSql(eventList)
//        println(getImpEventFromSqlRes(eventList.toList))
////        println(getImpPeopleFromSql(eventList.toList))

        val str = "{\"id\":\"1d00d31c4dcf4b2f8ca816dcaf70e557\",\"gridid\":\"440307003004018\",\"buildingid\":\"null\",\"reporteddate\":\"2020-11-18 10:16:23\",\"creator\":\"陈颖嫦\",\"acceptdepartment\":\"440307003004018\",\"source\":\"6\",\"kind\":\"2\",\"comenum\":\"1\",\"subkind\":\"207\",\"aim\":\"1\",\"threekind\":\"20706\",\"districtcode\":\"440307003004018\",\"location\":\"114.082133;22.657325\",\"place\":\"象角塘西五巷1-1号\",\"reportednum\":\"2\",\"amount\":\"null\",\"emergency\":\"null\",\"content\":\"西五巷1-1号404经网格员上\\'门核实发现没地线存在安全隐患。\",\"ishouse\":\"1\",\"housecode\":\"4403070030041200057000015\",\"isgroup\":\"0\",\"gatherer\":\"陈颖嫦\",\"gatherid\":\"null\",\"houseid\":\"4403070030041200057000015\",\"photosrc\":\"null\",\"syndate\":\"sysdate\",\"readtime\":\"null\",\"isread\":\"0\",\"remark\":\"null\",\"gisp_x\":\"114.082133\",\"gisp_y\":\"22.657325\",\"togetherpeople\":\"null\",\"houseaddress\":\"null\",\"levels\":\"null\"}"
        println(str)
        println(str.replaceAll("\\\\'","""'"""))
        println(str.replaceAll("""\\'""","""'"""))


    }

    /**
      * 从结果集中获取要插入到数据库的数据
      * @param eventList
      * @return
      */
    def getImpEventFromSqlRes(eventList: List[util.HashMap[String,String]]) ={

        val impEventList = eventList.map {
            hashmap => {
                var hm2 = hashmap
                var photoSrc: String = null
                var buildingid: String = "null" //看了系统里面之前同步的内容,这个字段默认为字符串null
                var housecode: String = null
                var houseid: String = null
                var address: String = null
                var togetherPeople: String = null
                val imagesJstr = hashmap.get("images".toUpperCase)
                if (imagesJstr != null) {
                    photoSrc = getPhotoSrc(imagesJstr)
                }
                hm2.put("PHOTOSRC", photoSrc)
                val bhJstr = hashmap.get("BuildingHouse".toUpperCase)
                if (bhJstr != null) {
                    val bhTuple = getBuildingHouse(bhJstr)
                    buildingid = bhTuple._1
                    housecode = bhTuple._2
                    houseid = bhTuple._3
                    address = bhTuple._4
                }
                hm2.put("BUILDINGID", buildingid)
                hm2.put("HOUSECODE", housecode)
                hm2.put("HOUSEID", houseid)
                hm2.put("ADDRESS", address)
                val sqrJstr = hashmap.get("sqr".toUpperCase)
                if (sqrJstr != null) {
                    togetherPeople = getTogetherPeople(sqrJstr)
                }
                hm2.put("TOGETHERPEOPLE", togetherPeople)
                hm2.put("SYNDATE", "sysdate")
                hm2.put("ISREAD", "0")
                hm2.replace("GATHERID", "null")
                getImpEventFromMap(hm2)
            }
        }
        impEventList
    }

//    hm: util.HashMap[String,String]
    private def getImpEventFromMap(hm: util.HashMap[String,String]) ={
        val fieldList = classOf[ImpEvent].getDeclaredFields.map(_.getName).toList
        val kvStrList = fieldList.map{
            field => {
                val value = hm.get(field.toUpperCase)
                s""""${field}":"${value}"""".stripMargin
            }
        }
        val eventJstr=s"""{${kvStrList.mkString(",")}}"""
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        var impEvent:ImpEvent=null
        try{
            impEvent = parse(eventJstr.replaceAll("""\\'""","""'""")).extract[ImpEvent]
        } catch {
            case e : JsonParseException => {
                e.printStackTrace()
                println("出错的json字符串为:"+eventJstr)
            }
            case e : Exception => {
                e.printStackTrace()
                println("出错了,未知错误")
            }
        }
        impEvent
    }

    def getImpPeopleFromSql(eventList: List[util.HashMap[String,String]]) ={
        val list = eventList.map {
            hashmap => {

                var sqrList: List[SqrInfo] = null

                val sqrJstr = hashmap.get("sqr".toUpperCase)
                if (sqrJstr != null) {
                    sqrList = getSqrCommon(sqrJstr)
                }
                val newSqrList = sqrList.map {
                    sqr => {
                        var sqrHashMap = new util.HashMap[String, String]()
                        var newID = ""
                        val conversationid = hashmap.get("CONVERSATIONID".toUpperCase)
                        val reporteddate = hashmap.get("REPORTEDDATE".toUpperCase)
                        val gatherer = hashmap.get("GATHERER".toUpperCase)
                        sqrHashMap.put("CONVERSATIONID",conversationid)
                        sqrHashMap.put("REPORTEDDATE",reporteddate)
                        sqrHashMap.put("GATHERER",gatherer)
                        sqrHashMap.put("ISREAD","0")

                        sqrHashMap.put("PHONE", getOrElse(sqr.phone))
                        sqrHashMap.put("SEX", getOrElse(sqr.sex))
                        sqrHashMap.put("ADDRESS", getOrElse(sqr.address))
                        sqrHashMap.put("NAME", getOrElse(sqr.pname))
                        sqrHashMap.put("CARDNO", getOrElse(sqr.cardno))
                        sqrHashMap.put("STYPE", getOrElse(sqr.`type`))
                        sqrHashMap.put("CREDATE", "sysdate")
                        sqrHashMap.put("MODIFYDATE", "null")
                        sqrHashMap.put("CREDATE", "null")
                        if (sqr.pname == null) {
                            newID = conversationid + sqr.pname + sqr.`type`
                        } else {
                            newID = conversationid + sqr.pname
                        }
                        sqrHashMap.put("ID", newID)
                        getImpPeopleFromMap(sqrHashMap)
                    }
                }
                newSqrList
                //                new ImpPeople()
            }
        }.flatMap(_.toList)
        list
    }

    def getImpPeopleFromMap(hm: util.HashMap[String,String]) ={
        val fieldList = classOf[ImpPeople].getDeclaredFields.map(_.getName).toList
        val kvStrList = fieldList.map{
            field => {
                val value = hm.get(field.toUpperCase)
                s""""${field}":"${value}"""".stripMargin
            }
        }
        val eventJstr=s"""{${kvStrList.mkString(",")}}"""
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        var impPeople:ImpPeople=null
        try{
            impPeople = parse(eventJstr.replaceAll("""\\'""","""'""")).extract[ImpPeople]
        }catch{
            case e : JsonParseException => {
                e.printStackTrace()
                println("出错的json字符串为:"+eventJstr)
            }
            case e : Exception => {
                e.printStackTrace()
                println("出错了,位置错误")
            }
        }

        impPeople
    }


    /**
      * 从event_sqr字段中取出共同诉求人的信息，多个共同诉求人取第一个
      * @param jsonStr
      * @return
      */
    def getTogetherPeople(jsonStr: String)={
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        var togetherpeople: String = null
        var peoples: List[String]=null

        if (jsonStr!=null && jsonStr.contains("[") && jsonStr.contains("]") && jsonStr.contains("\"type\":\"2\"")){
            //此处使用数组方式解析方式，是因为type为2的可能有多个
            val sqrArr = getSqrCommon(jsonStr)
            peoples = sqrArr.map {
                sqr => {
                    var people: String = null

                    if (sqr.`type`=="2") {
                        var sex = ""
                        sqr.sex match {
                            case "1" => sex = "男"
                            case "2" => sex = "女"
                            case _ => sex = "undefined"
                        }
                        //此处的undefined 是由于sex这个变量在json字符串中不存在，原来的处理方式是写一个undefined，此处使用原来的方式
                        people = s"${sqr.pname} ${sex} ${sqr.age} ${sqr.phone} ${sqr.address} ${sqr.cardno}"

                    }
                    println(people)
                    people
                }
            }

        }
        if (peoples!=null) {
            togetherpeople = peoples.filter(_!=null)(0)
        }
        togetherpeople
    }


    def getSqrsInfo(jsonStr: String)={
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        var sqrs: List[SqrInfo]=null

        if (jsonStr!=null && jsonStr.contains("[") && jsonStr.contains("]")){
            sqrs = getSqrCommon(jsonStr)
        }

        sqrs
    }

    /**
      * 通过images字段获取照片的绝对路径
      * @param jsonStr
      * @return
      */
    def getPhotoSrc(jsonStr: String) ={
        var photosrc: String=null
        if (!jsonStr.contains(".bmp]") || !jsonStr.contains(".bmp,") || jsonStr.contains("{") || jsonStr.contains("null")){
//            val newJsonStr = jsonStr.replaceAll("""\\\"""", """"""")
//
//            println(
//                s"""
//                   |替换前jsonStr=>${jsonStr}
//                   |替换后jsonStr=>${newJsonStr}
//                 """.stripMargin)
            try{
                val value = parse(jsonStr.replaceAll("""\\\"""", """""""))
                implicit val formats = Serialization.formats(ShortTypeHints(List()))
                val nameedPath = (value \ "nameedPath").extract[String]
                val name = (value \ "name").extract[String]
                photosrc = s"${Constants.PHOTOURL}${nameedPath}/${name}"
            }catch{
                case e: Exception => {
                    e.getStackTrace
                    println("出错的json为: "+jsonStr)
                }
            }

        }
        photosrc
    }

    /**
      * 通过buildinghouse字段获取事件的楼栋及房间相关信息
      * @param jsonStr
      * @return
      */
    def getBuildingHouse(jsonStr: String) ={
        var buildingid: String=null
        var housecode: String=null
        var houseid: String=null
        var address: String=null
        if (jsonStr != null || jsonStr!=("null")){
            var valueArr:JValue=null
            try{
                valueArr = parse(jsonStr.replaceAll("""\\\"""", """""""))
            }catch{
                case e:JsonParseException=>{
                    println(s"出错的json为： ${jsonStr}")
                    e.printStackTrace()
                }
                case e:Exception=>{
                    println(s"出错的json为： ${jsonStr}")
                    e.printStackTrace()
                }
            }
            implicit val formats = Serialization.formats(ShortTypeHints(List()))
            val value = valueArr.children(0)
            buildingid = (value \ "buildingid").extract[String]
            housecode = (value \ "code").extract[String]
            houseid = (value \ "code").extract[String]
            address = (value \ "address").extract[String]
        }
        (buildingid,housecode,houseid,address)
    }

    /**
      * 获得一个json数组字符串下面的所有json对象
      * @param jsonStr
      * @return
      */
    @deprecated
    def getJsonStrAllChild(jsonStr: String) ={
        val str = jsonStr.substring(jsonStr.indexOf("[")+1, jsonStr.indexOf("]"))
        val strArr = str.split("},").map(_+"}").map(_.replace("}}","}"))

        val sqrArr = strArr.map {
            json => {
                var sqr: Any = null
                if (json.contains("\"sex\"")) {
                    sqr = getSqrWithoutsex(json)
                } else {
                    sqr = getSqrWithoutsex(json)
                }
                sqr
            }
        }

        sqrArr
    }

    @deprecated
    def getSqrWithoutsex(jsonStr: String)={
        val valueArr = parse(jsonStr)
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        val sqr = valueArr.extract[SqrWithoutSex]

        sqr
    }

    @deprecated
    def getSqrWithsex(jsonStr: String)={
        val valueArr = parse(jsonStr)
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        val sqr = valueArr.extract[SqrWithSex]

        sqr
    }

    /**
      * 获得一个json数组字符串下面的所有json对象
      * @param jsonStr
      * @return
      */
    private def getSqrCommon(jsonStr: String)={

        var valueArr:JValue=null
        try{
            valueArr = parse(jsonStr.replaceAll("""\\\"""", """""""))
        }catch{
            case e:JsonParseException=>{
                println(s"出错的json为： ${jsonStr}")
                e.printStackTrace()
            }
            case e:Exception=>{
                println(s"出错的json为： ${jsonStr}")
                e.printStackTrace()
            }
        }
        implicit val formats = Serialization.formats(ShortTypeHints(List()))
        val sqrArr = valueArr.children.map{
            jv => {
                val `type` = (jv \ "type").extractOrElse[String](null)
                val pname = (jv \ "pname").extractOrElse[String](null)
                val age = (jv \ "age").extractOrElse[String](null)
                val cardno = (jv \ "cardno").extractOrElse[String](null)
                val address = (jv \ "address").extractOrElse[String](null)
                val phone = (jv \ "phone").extractOrElse[String](null)
                val sex = (jv \ "sex").extractOrElse[String](null)
                new SqrInfo(`type`,pname,age,cardno,address,phone,sex)
            }
        }

        sqrArr
    }

    def getOrElse(ori: String, tgt: String = "null") ={
        var res: String = tgt
        if (ori!=null && ori!="" && ori.length!=0) {
            res=ori
        }
//        if () {
//            res=ori
//        }
        res
    }


}
